package com.weather.mobile.job;

import com.weather.mobile.client.CityClient;
import com.weather.mobile.domain.City;
import com.weather.mobile.domain.WeatherResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Service
public class CacheWeatherDataJob {
    @Autowired
    CityClient cityClient;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    RedisTemplate redisTemplate;

    @Scheduled(cron="0 * * * * ?")
    public void cacheWeatherData(){
        List<City> cityList=cityClient.cityList();

        for(City city:cityList){
            //1.访问第三方接口获取数据
            String url="https://apis.tianapi.com/tianqi/index?key="+"2af8ed08605c20f76f8183d1b702474b"+"&city="+city+"&type=7";
            System.out.println("url:"+url);
            WeatherResponse weatherResponse=restTemplate.getForObject(url, WeatherResponse.class);

            //2.放入缓存
            redisTemplate.opsForHash().put("mobileweatherdata",city,weatherResponse);
        }
    }
}
